// pages/confirmOrder/confirmOrder.js
let http = require('../../utils/request.js')
let path = getApp().globalData.path
const filter = require('../../utils/filter.js');
Page(filter.loginCheck({

  /**
   * 页面的初始数据
   */
  data: {
    Tname: '确认订单',
    array: ['快递', '自提', '配送'],
    index: 0,
    sendType: 1,
    baseurl: path
  },
  // message
  message(e) {
    this.setData({
      message: e.detail.value
    })
  },
  // 快递方式
  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let sendType = Number(e.detail.value) + 1
    this.setData({
      index: e.detail.value,
      sendType
    })
  },
  // 选择地址
  goAddressChoose(e) {
    wx.navigateTo({
      url: '/pages/addressChoose/addressChoose',
    })
  },
  // 下单
  /**
   * 【购】购物车下单所需参数 / 【商】商城下单所需参数
   * @param scene {number} 【购】 下单类型：1=商城订单 2=报名 3=赛事
   * @param address_id {string} 【商】【购】地址ID
   * @param cart_id {number} 【购】购物车ID
   * @param goods_id {number} 【商】商品ID
   * @param goods_num {number} 【商】【购】商品数量
   * @param remark {string} 【商】【购】备注
   * @param freights {number} 【商】【购】运费
   * @param pay_type {number} 【商】【购】支付类型：1=零钱 2=积分
   * @param money {number} 【商】【购】订单总金额
   * @param delivery {number} 【商】【购】快递类型：1=快递 2=自提 3=配送
   */
  pushOrder(e) {
    let _this = this
    let buyType = wx.getStorageSync('buyType') //buyType 购买渠道   1=商城购买 2=购物车购买
    if (buyType == 1) {
      if (_this.data.addId) {
        // 商城购买
        http.postHttp('/create_order', {
          scene: 1,
          address_id: _this.data.addId,
          goods_id: _this.data.goodsid,
          goods_num: _this.data.goodsnum,
          remark: _this.data.message,
          freights: _this.data.thisSendMoney,
          pay_type: 1,
          money: _this.data.price,
          delivery: _this.data.sendType,
          label: _this.data.unit

        }, {}).then(res => {
          // console.log(res, 'payfor')
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp,
            nonceStr: res.data.data.nonceStr,
            package: res.data.data.package,
            signType: 'MD5',
            paySign: res.data.data.paySign,
            success(res) {
              // console.log('支付成功')
              wx.redirectTo({
                url: '/pages/orderCenter/orderCenter',
              })
            },
            fail(res) {
              wx.redirectTo({
                url: '/pages/orderCenter/orderCenter',
              })
            }
          })
        })
      } else {
        wx.showToast({
          title: '请补全信息',
          icon: 'none'
        })
      }
    } else {
      console.log(_this.data.addId)
      debugger
      if (_this.data.addId) {
        // 购物车购买
        http.postHttp('/create_order', {
          scene: 1,
          address_id: _this.data.addId,
          cart_id: _this.data.result,
          goods_num: _this.data.goodsnum,
          remark: _this.data.message,
          freights: _this.data.thisSendMoney,
          pay_type: 1,
          money: _this.data.sumPrice,
          delivery: _this.data.sendType,
          label: _this.data.unit

        }, {}).then(res => {
          // console.log(res, 'payfor')
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp,
            nonceStr: res.data.data.nonceStr,
            package: res.data.data.package,
            signType: 'MD5',
            paySign: res.data.data.paySign,
            success(res) {
              console.log('支付成功')
              wx.redirectTo({
                url: '/pages/orderCenter/orderCenter',
              })
            },
            fail(res) {
              wx.redirectTo({
                url: '/pages/orderCenter/orderCenter',
              })
            }
          })
        })
      } else {
        wx.showToast({
          title: '请补全信息',
        })
      }
    }

  },
  // 积分支付
  pushOrderIntegral(e) {
    let _this = this
    let buyType = wx.getStorageSync('buyType') //buyType 购买渠道   1=商城购买 2=购物车购买
    if (_this.data.integral !== 0 || buyType == 1) {
      http.postHttp('/create_order', {
        scene: 1,
        address_id: _this.data.addId,
        goods_id: _this.data.goodsid,
        goods_num: _this.data.goodsnum,
        remark: _this.data.message,
        freights: _this.data.thisSendMoney,
        pay_type: 2,
        money: _this.data.integral,
        delivery: _this.data.sendType
      }, {}).then(res => {
        console.log(res, '积分支付')
        if (res.data.code == 1) {
          wx.redirectTo({
            url: '/pages/orderCenter/orderCenter',
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this
    let cate_id = wx.getStorageSync('cate_id')
    let buyType = wx.getStorageSync('buyType')
    let unit = options.unit
    let isIntegral = options.isIntegral
    this.setData({
      unit,
      isIntegral
    })

    // 根据buyType购买渠道区分请求数据
    if (buyType == 1) {
      let goodsid = options.goodsid
      let price = options.price
      this.setData({
        goodsid,
        price,
      })
      let goodsnum = 1
      http.getHttp('/shop_goods_detail', {
        goods_id: goodsid,
      }, {}).then(res => {

        let tmpArr = res.data.data
        let integral = res.data.data.integral
        this.setData({
          tmp: tmpArr,
          goodsnum,
          integral
        })
      })
    } else {
      let result = options.result
      let sumPrice = options.sumPrice
      // console.log(options.sumPrice, 'options.sumPrice')
      // console.log(Number(sumPrice), _this.data.thisSendMoney, 'a')
      this.setData({
        sumPrice,
        result,
      })
      // 请求商品数据
      http.getHttp('/user_cart', {
        page: 1,
        limit: 10,
        cart_id: result
      }, {
        token: wx.getStorageSync('token')
      }).then(res => {
        console.log(res, 'cartConfi')
        let goodsnum = 0
        let tmpArr = res.data.data
        tmpArr.forEach(function (val, index) {
          goodsnum += val.goods_num //商品数量
        })
        this.setData({
          goodsnum,
          tmp: tmpArr,

        })
      })
    }
    // 请求运费
    http.getHttp('/get_freight', {
      address_id: _this.data.addId,
      cart_id: _this.data.result,
      goods_num: _this.data.goodsnum
    }, {
      token: wx.getStorageSync('token')
    }).then(res => {
      let sendMoney = res.data.data
      let thisSendMoney = res.data.data.freight_money
      // console.log(sendMoney,'sendMoney')
      // console.log(res.data.data.freight_money)
      this.setData({
        sendMoney,
        thisSendMoney
      })
      // console.log(res,'运费')
    })




    this.setData({
      buyType,
      cate_id, //商城tabID  2为积分商城
      // ['tmp.price']:Number(_this.data.price)+Number(_this.data.thisSendMoney),
      // ['sumPrice']:Number(_this.data.sumPrice)+Number(_this.data.thisSendMoney),

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
    if(this.data.flag==1){
      let tmpAddress = {
        'addressid': this.data.addressid,
        'name': this.data.name,
        'phone': this.data.phone,
        'province': this.data.province,
        'city': this.data.city,
        'area': this.data.area,
        'position': this.data.position,
        'addId':this.data.addressid
      }
      this.setData({
        tmpAddress
      })
    }else{
         // 请求地址数据
      http.getHttp('/user_address', {}, {
        token: wx.getStorageSync('token')
      }).then(res => {
        if (res.data.data.length !== 0) {
          let tmpAdd = res.data.data
          // let defaultAddress = tmpAdd.slice(0, 1)
          let tmpAddress = tmpAdd[0]
          let addId = tmpAdd[0].id
          this.setData({
            tmpAddress,
            addId
          })
        } else {
          wx.showToast({
            title: '暂无地址',
            icon: 'none'
          })
        }
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // var that = this;
    // // 显示加载图标
    // wx.showLoading({
    //   title: '玩命加载中',
    // })
    // // 页数+1
    // page = page + 1;
    // http.getHttp('/user_cart',{},{}).then(res=>{
    //   var moment_list = that.data.moment;
    //     const oldData = that.data.moment;
    //     that.setData({
    //        moment:oldData.concat(res.data.data)
    //     })
    //     // 隐藏加载框
    //     wx.hideLoading();
    // })

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
}))